<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="年份" prop="weekYear">
        <el-input
          v-model="queryParams.weekYear"
          placeholder="请输入年份"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="第几周" prop="weekNumber">
        <el-input
          v-model="queryParams.weekNumber"
          placeholder="请输入第几周"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SCHOOL_CHECK_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['school:recipe-menus-weekly:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 智能配餐
        </el-button>
        <!-- <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['school:recipe-menus-weekly:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['school:recipe-menus-weekly:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="menuId"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column label="编号" align="center" prop="menuId" /> -->
      <el-table-column label="年份" align="center" prop="weekYear" />
      <el-table-column label="第几周" align="center" prop="weekNumber" />
      <el-table-column
        label="开始日期"
        align="center"
        prop="weekStartDate"
        :formatter="dateFormatter2"
        width="180px"
      />
      <el-table-column
        label="结束日期"
        align="center"
        prop="weekEndDate"
        :formatter="dateFormatter2"
        width="180px"
      />

      <el-table-column label="食谱周期(天)" align="center" prop="days" />
      <el-table-column label="备注" align="center" prop="remark" />

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SCHOOL_CHECK_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="right" min-width="120px">
        <template #default="scope">
          <!-- 当status =1 并且当前用户是审核人员时显示 -->
          <el-button
            v-if="scope.row.status === 1 && auditorUserIds.includes(userId)"
            link
            type="success"
            @click="handleApprove(scope.row)"
            v-hasPermi="['school:recipe-menus-weekly:update']"
          >
            审核
          </el-button>

          <el-button
            link
            type="primary"
            v-hasPermi="['school:recipe-menus-weekly:update']"
            @click="handleViewRecipe(scope.row.menuId)"
          >
            查看食谱
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.menuId)"
            v-hasPermi="['school:recipe-menus-weekly:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <RecipeMenusWeeklyForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { RecipeMenusWeeklyApi, RecipeMenusWeekly } from '@/api/school/recipe/menusWeekly'
import { RecipeConfigApi } from '@/api/school/recipe/config'
import RecipeMenusWeeklyForm from './RecipeMenusWeeklyForm.vue'
import { ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user'

/** 周食谱 列表 */
defineOptions({ name: 'RecipeMenusWeekly' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter() // 路由
const userStore = useUserStore() // 用户信息

const loading = ref(true) // 列表的加载中
const list = ref<RecipeMenusWeekly[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  weekYear: undefined,
  weekNumber: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const auditorUserIds = ref<number[]>([]) // 审核人员ID列表
const userId = computed(() => userStore.getUser.id) // 当前用户ID

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await RecipeMenusWeeklyApi.getRecipeMenusWeeklyPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取审核人员配置 */
const getAuditorConfig = async () => {
  try {
    const data = await RecipeConfigApi.getRecipeConfig()
    // 解析审核人员ID列表
    if (data && data.userIds) {
      auditorUserIds.value = Array.isArray(data.userIds) ? data.userIds : JSON.parse(data.userIds)
    }
  } catch (err) {
    console.error('获取审核人员配置失败', err)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const approveMeetingReserve = async (id, status) => {
  try {
    const res = await RecipeMenusWeeklyApi.approveRecipeMenusWeekly({
      id,
      status
    })
    if (res) {
      message.success('审核完成')
      await getList()
    }
  } catch (e) {
    message.error((e as string) || '审核失败')
  }
}
/** 审核操作 */
const handleApprove = async (row: any) => {
  try {
    const action = await ElMessageBox.confirm(
      `确定要审核第${row.weekYear}年第${row.weekNumber}周食谱吗？`,
      '审核',
      {
        distinguishCancelAndClose: true,
        confirmButtonText: '通过',
        cancelButtonText: '拒绝',
        type: 'warning'
      }
    )

    if (action === 'confirm') {
      // 发起删除
      approveMeetingReserve(row.menuId, 0)
    }
  } catch (error) {
    // 用户取消操作时不显示错误信息
    if (error !== 'cancel' && error !== 'close') {
      message.error('审核操作失败')
    }
    if (error === 'cancel') {
      approveMeetingReserve(row.menuId, 2)
    }
  }
}

/** 查看食谱 */
const handleViewRecipe = (menuId: number) => {
  router.push({
    name: 'WeeklyRecipe',
    query: { menuId: menuId, pageNo: queryParams.pageNo, pageSize: queryParams.pageSize }
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RecipeMenusWeeklyApi.deleteRecipeMenusWeekly(id)
    message.success(t('common.delSuccess'))
    // currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除周食谱 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await RecipeMenusWeeklyApi.deleteRecipeMenusWeeklyList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: RecipeMenusWeekly[]) => {
  checkedIds.value = records.map((item) => item.menuId)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RecipeMenusWeeklyApi.exportRecipeMenusWeekly(queryParams)
    download.excel(data, '周食谱.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await getAuditorConfig()
  getList()
})
</script>
